package com.netcracker.educenter.filestorage.servlets.security.authorization;

import com.netcracker.educenter.filestorage.configurator.Configurator;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns = "/user/*")
public class AuthorizationFilter implements Filter {

    private static final Logger log = Logger.getLogger(AuthorizationFilter.class);
    private static final String LOGIN_PAGE = Configurator.getConfigurator().getLoginPageUrl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String userName = (String)request.getSession().getAttribute("authorized_user");

        try {
            if (userName == null) {

                HttpServletResponse response = (HttpServletResponse)servletResponse;
                response.sendRedirect(request.getContextPath() + LOGIN_PAGE);

            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            log.error("cannot go to page", e);
        }
    }

    @Override
    public void destroy() {

    }
}
